package com.jt.service;

import com.jt.config.RedisLockConfig;
import com.jt.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;


@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisLockConfig redisLockConfig;

    @Override
    public void lockMethod() {
        String lockKey = "liushuhong";
        String uuid = "36604537";
        long expireTime = 10000; // 10 seconds
        try {
            boolean b = redisLockConfig.setLock(lockKey, uuid, expireTime, TimeUnit.MILLISECONDS);
            if (b) {
                // 获取到锁，执行需要同步的操作
                System.out.println(new Date() + "获取锁"+lockKey+"成功");
                // 模拟业务操作
                Thread.sleep(5000);
            } else {
                System.out.println(new Date() + "获取锁"+lockKey+"失败");
            }
        } catch (Exception e) {
            Thread.currentThread().interrupt();
        } finally {
            redisLockConfig.deleteLock(lockKey, uuid);
        }
    }
}
